"""
根据传入的参数，进行路径规划
"""
import ast
import json

import numpy as np
from flask import Blueprint, request, jsonify
from algorithm.geneticAlgorithm.genetic import genetic_result, genetic_display
from server.utils.formatData import format_request_params

route_genetic_algorithm = Blueprint('algorithm/genetic', __name__)


# 遗传算法规划路径
@route_genetic_algorithm.route('/get_path', methods=['POST'])
def get_path():
    if request.method == 'POST':
        data = request.get_json()
        print(data)
        nodes, edges = genetic_result(data)
        print(nodes, edges)
        response_data = {
            'nodes': nodes,
            'edges': edges
        }
        return jsonify(response_data)


# 遗传算法可视化中间结果
@route_genetic_algorithm.route('/get_display', methods=['POST'])
def get_display():
    if request.method == 'POST':
        request.form = format_request_params(request.form)
        start_node = request.form.get('start_node')
        goal_node = request.form.get('goal_node')
        key_nodes = request.form.get('key_nodes')

        nodes_data = request.form.get('nodes_data')
        edges_data = request.form.get('edges_data')

        cost_v = np.array(request.form.get('cost_v'))
        cost = np.array(request.form.get('cost'))
        edges = np.array(ast.literal_eval(request.form.get('edges').replace('false', 'False').replace('true', 'True')))

        maxGen = request.form.get('maxGen')
        packNum = request.form.get('packNum')
        mutationP = request.form.get('mutationP')
        crossP = request.form.get('crossP')

        data = {
            'startNode': start_node,
            'targetNode': goal_node,
            'keyNodes': key_nodes,
            'nodesData': nodes_data,
            'edgesData': edges_data,
            'costV': cost_v,
            'cost': cost,
            'edges': edges,
            'maxGen': maxGen,
            'packNum': packNum,
            'mutationP': mutationP,
            'crossP': crossP,
        }

        # print(data)
        result = genetic_display(data)
        # print(json.dumps(result))
        return jsonify(result)
